﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Models.Common.Enums;
using HamcoWcs.Models.Devices;
using Microsoft.EntityFrameworkCore;
using System.Linq;

namespace HamcoWcs.Service.Pcon.PconPlcDbMsgParsers
{
    public class PconMsgParse_PalletOut : PconMsgParseBase
    {
        private readonly ILoggerService _logger;
        private readonly IBaseTaskService _baseTaskService;
        public override EnumPconPlcRequest RequestType => EnumPconPlcRequest.PalletOut;

        public PconMsgParse_PalletOut(IMapper mapper, WcsDbContext wcsDbContext,
            IBaseTaskService baseTaskService, ILoggerService logger)
            : base(null, wcsDbContext, mapper)
        {
            _baseTaskService = baseTaskService;
            _logger = logger;
        }
        public override void Deal(PconDto pconDto, PconPlc pconPlc)
        {
            if (pconDto.PconType == EnumPconType.Lift || pconDto.PconType == EnumPconType.RGV)
            {
                //_logger.AddWcsRunLog(pconDto.UnitId, $"{pconDto.DeviceName}到达，{pconDto.UnitId}搬入");
            }

            if (pconDto.PconType == EnumPconType.RGV)
            {
                var taskEntity = _wcsDbContext.SubTasks.AsQueryable()
                                          .Where(x => x.TaskStatus == EnumSubTaskStatus.OnProgress.ToString())
                                          .Where(x => x.ToLoc == pconDto.MachineName)
                                          .Where(x => x.UnitId == pconDto.UnitId)
                                          .Include(x => x.MainTask)
                                          .FirstOrDefault();
                if (taskEntity == null)
                    return;
                taskEntity.StartTime = System.DateTime.Now;
                _wcsDbContext.SaveChanges();
                _baseTaskService.UpdateSubTaskStatus(taskEntity.Id, EnumSubTaskStatus.Finished);
            }
        }
    }
}
